/**
 * Created by xqing on 2018/2/28.
 */
/**
 * Created by xqing on 2017/12/5.
 */

;(function (w, $) {
    function appActivity(opts) {
        var defaultOpts = {
            node: null
        };
        /**
         * 参数合并
         */
        this.opts = $.extend(defaultOpts, opts);
        /**
         * 请求URL
         * @type {{url1: string}}
         */

        this.url = {
            //登陆
            login:'http://h5vote.sctv.com:28282/h5voteengine/login.do',
            // login:'http://uisact.sctv.com:28080/uas/user/loginByToken',
            //抽奖（输入兑换码） 测试服host指向 192.168.60.113 xqtest.sctv.com
            // getLottery:'http://192.168.60.113:9080/api/lottery/award/getLottery',
            getLottery:'http://uisact.sctv.com:28080/api/lottery/award/getLottery',
            //实物奖品填写用户信息
            // userApply:'http://192.168.60.113:9080/api/lottery/award/apply',
            userApply:'http://uisact.sctv.com:28080/api/lottery/award/apply'




        };
        /**
         * tag参数
         * @type {{pandaVideo: string, pandaWowtv: string, scfocus: string, iptvvote: string}}
         */
        this.platform={
            pandaVideo:"392861C427FE30420D959D043CD32FFD",
            pandaWowtv:"A9A2320BDB0006D83963CCFF2FF7E3A0",
            scfocus:"FAF092CD57FCF2F335AA0BD2658E817B",
            iptvvote:"189670BE1410EE9DA7DDD7E9DDFEFF7A",
            pc:"41357B790F3A7A90B2A529BEEF629C43"
        };

        /**
         * 是否已登陆
         * @type {boolean}
         */
        this.login = true;
        /**
         * 是否使用mock数据
         * @type {boolean}
         */
        this.mock = false;
        /**
         * 用户token
         * @type {string}
         */
        this.token = '';
        /**
         * 抽奖活动id
         * @type {number}
         */
        this.actId = 184;

        this.lotteryMock =  {
            "id": null,
            "levelName": 3,
            "itemName": "小米净化器",
            "needInfo": 1
        };






        this._init();







    }
    $.extend(appActivity.prototype, {
        /**
         * 初始化入口
         * @private
         */
        _init: function () {
            var self = this;
            self._loadingCheck();
            self._uiBind();

            $('#test').on('click',function () {
                self._loginCheck();
            })
        },
        /**
         *
         * @private
         */
        _loadingCheck: function(){
            var self = this;

            window.onload = self._loginCheck();

        },
        /**
         * 检查cookie中是否已有userToken 有的话拼接到url中重载页面
         * 检查url中是否有token 有的话进行登陆
         * @private
         */
        _loginCheck: function () {
            var self = this,
                thisUrl = window.location.href,
                urlParaString = null,
                paraArr = null,
                paraToken = null,
                loginJson = {};
            //读取cookie
            function getCookie(name) {
                var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
                if(arr=document.cookie.match(reg))
                    return unescape(arr[2]);
                else
                    return null;
            }
            if(thisUrl.indexOf('token') > -1){
                urlParaString = window.location.href.split("?")[1];
                if (typeof(urlParaString)!='undefined'){
                    paraArr = urlParaString.split("&");
                    paraToken = paraArr[0].split("token=")[1];
                }
                loginJson.Token = paraToken;
                self.token = paraToken;
                loginJson.Uid = 'id111';
                if(self.mock){
                    self._loginSucc(self.loginMock);
                }else {
                    $.ajax({
                        type: "post",
                        url: self.url.login,
                        data: JSON.stringify(loginJson),
                        contentType: "application/json;charset=utf-8",
                        dataType: "json",
                        success: function(data){
                            self._loginSucc(data);
                        }
                    });
                }

            }else {
                if(getCookie('userToken')){
                    window.location.href = thisUrl + '?token=' + getCookie('userToken');
                }else {
                    //未登录呼起app登录
                    // console.log('未登录');
                    $('#j-login').trigger('click');
                }
            }


        },

        /**
         * 必填项检查
         * @param node
         * @private
         */
        _checkMust: function (node) {
            var flag = true;
            $(node).each(function (i) {
                var checkTxt = $.trim($(node[i]).val());
                if(checkTxt == ''){
                    $(node[i]).addClass('error');
                    flag = false;
                    return false;
                }else {
                    flag = true;
                }
            });
            return flag;
        },


        /**
         * 交互事件绑定

         * @private
         */
        _uiBind: function () {
            var self = this;
            var wrapper = $(self.opts.node);
            //验证兑换码
            wrapper.delegate('.j_get_lottery','click',function () {
                var $this = $(this);
                var node = $this.parents('.convert');
                if(self._checkMust(node.find('input.must')) ){

                    $.ajax({
                        type: "get",
                        url: self.url.getLottery,
                        // data: JSON.stringify(self._getLotteryJson(node)),
                        data: self._getLotteryJson(node),
                        contentType: "application/json;charset=utf-8",
                        dataType: "json",
                        success: function(data){
                            self._getLotterySucc(data);
                        },
                        error: function (data) {
                            var res = JSON.parse(data.responseText);
                            alert(res.err);
                        }
                    });

                }
            });

            wrapper.delegate('.j_user_apply','click',function () {
                var $this = $(this);
                var node = $this.parents('.fill-info');
                var jsonUrl = self.url.userApply+'?token='+self.token+'&actId='+self.actId+'&platform='+self.platform.pandaVideo;


                if(self._checkMust(node.find('input.must')) ){

                    $.ajax({
                        type: "post",
                        url: jsonUrl,
                        data: JSON.stringify(self._userApplyJson(node)),
                        contentType: "application/json;charset=utf-8",
                        dataType: "json",
                        success: function(data,XMLHttpRequest,xhr){
                            console.log(data);
                            console.log(xhr.status);
                            $('.j-apply-popup').removeClass('hide');
                        },
                        error: function (data) {
                            var res = JSON.parse(data.responseText);
                            alert(res.err);
                        }

                    });

                }
            });




        },
        /**
         * 获取问题-json
         * @param node
         * @returns {*}
         * @private
         * 入参：
         * token
         * actId 写死
         * platform
         * inviteCode
         */


        _getLotteryJson: function (node) {
            var self = this;
            var getLJson = {};
            var inviteCode = node.find('.convert-code').val();

            getLJson.token = self.token;
            getLJson.actId = self.actId;
            getLJson.platform = self.platform.pandaVideo;
            getLJson.inviteCode = inviteCode;
            return getLJson
        },
        /**
         * 抽奖出参处理
         * {"actawardawardForWeb": {
                    "id": 奖品id,
                    "mId": 操作记录id,
                    "levelName": "奖品等级",
                    "itemName": "奖品名称",
                    "needInfo": 1,是否需要填写用户信息 0不需要 1需要
                    "emptyactAward": 是否为空奖 0是1不是（谢谢参与）
                },
                "code": 200
            }
         * @param data
         * @private
         */
        _getLotterySucc:function(data){


        },
        /**
         * 获取问题，成功回调
         *
         * @param data
         * @private
         */
        _sssss:function (data) {
            console.log(data.itemName);
            var self = this;
            var temHtml = '';
            if(data.needInfo == 0){
                if(data.levelName == 0){
                    temHtml += '<div class="prize"> ' +
                        '<div class="prize1"> ' +
                        '<i class="prize-icon prize-icon-'+data.levelName+'"></i> ' +
                        '<p class="prize-name">恭喜您，获得</p> ' +
                        '<p class="prize-name">'+data.itemName+'</p> ' +
                        '<p class="prize-info"> 领券链接：<a href="https://m.mobike.com/h5/ten_coupons/zh/index.html?src=028001&citycode=029"> 点此领券</a></p> ' +
                        '</div> ' +
                        '<div class="img-area"> ' +
                        '<img src="http://app.sctv.com/tv/event/HD_DLH5/img/prize-info-img'+data.levelName+'.jpg"> ' +
                        '</div> ' +
                        '</div>';
                }else if(data.levelName == 1){
                    temHtml += '<div class="prize"> ' +
                        '<div class="prize1"> ' +
                        '<i class="prize-icon prize-icon-'+data.levelName+'"></i> ' +
                        '<p class="prize-name">恭喜您，获得</p> ' +
                        '<p class="prize-name">'+data.itemName+'</p> ' +
                        '</div> ' +
                        '<div class="img-area"> ' +
                        '<img src="http://app.sctv.com/tv/event/HD_DLH5/img/prize-info-img'+data.levelName+'.jpg"> ' +
                        '</div> ' +
                        '</div>';
                }

            }else {
                temHtml += '<div class="prize"> ' +
                    '<div class="prize1"> ' +
                    '<i class="prize-icon prize-icon-'+data.levelName+'"></i> ' +
                    '<p class="prize-name">恭喜您，获得</p> ' +
                    '<p class="prize-name">'+data.itemName+'</p> ' +
                    '</div> ' +
                    '</div>'+
                    '<div class="fill-info" >' +
                    '<p class="fill-title">完善领奖信息 奖品即将为您寄送</p> ' +
                    '<div class="input-area "> ' +
                    '<table>' +
                    '<tr> ' +
                    '<td> ' +
                    '<label>姓&nbsp;&nbsp;&nbsp;&nbsp;名</label> ' +
                    '</td> ' +
                    '<td colspan="2"> ' +
                    '<input class="must username" type="text" placeholder="请报上大名"> ' +
                    '</td> ' +
                    '</tr> ' +
                    '<tr> ' +
                    '<td> ' +
                    '<label>电&nbsp;&nbsp;&nbsp;&nbsp;话</label> ' +
                    '</td> ' +
                    '<td colspan="2"> ' +
                    '<input class=" must phone" type="text" placeholder="输入参与本次活动的号码哦"> ' +
                    '</td> ' +
                    '</tr> ' +
                    '<tr> ' +
                    '<td> ' +
                    '<label>地&nbsp;&nbsp;&nbsp;&nbsp;址</label> ' +
                    '</td> ' +
                    '<td colspan="2"> ' +
                    '<input class="must address" type="text" placeholder="有了地址，奖品才能飞奔而来哦"> ' +
                    '</td> ' +
                    '</tr> ' +
                    '</table> ' +
                    '<div class="tips"></div> ' +
                    '<p class="submit-btn active j_user_apply">领取 </p> ' +
                    '</div> ' +
                    '</div>';
            }
            $(self.opts.node).html(temHtml);


        },
        /**
         * 提交答案-json
         * @param node
         * @returns {*}
         * @private
         * 入参
         *
         * Request body
         */

        _userApplyJson: function (node) {
            var self = this;
            var userApplyJson = {};

            var username = node.find('input.username');
            var phone = node.find('input.phone');
            var address = node.find('input.address');

            userApplyJson.userName = username.val();
            userApplyJson.phone = phone.val();
            userApplyJson.address = address.val();

            console.log(userApplyJson);
            return userApplyJson;


        },





        _loginSucc: function(returnJson){
            // alert(returnJson.code);
            if(returnJson.code != 200){
                //未登录呼起app登录
                // console.log('未登录');
                $('#j-login').trigger('click');
            }

        },


        /**
         * 重新加载
         */
        reload: function () {
            this._init();
        }
    });

    /**
     * 暴露全局变量
     */
    if (!w.appActivity) {
        w.appActivity = function () {
            $('.j_app_wrapper').each(function () {
                new appActivity({
                    node: this
                });

            });
        };
    }

    /**
     * banner入口
     */
    $(function () {
        w.appActivity();
    });

})(window, jQuery);